<template>
  <!--分配权限-->
  <el-card style="width: 100%;height: 100%">
    <div slot="header">{{ roleInfo.roleName }}</div>
    <el-tree
      :data="menuList"
      :default-checked-keys="checkedArr"
      :props="defaultProps"
      node-key="id"
      show-checkbox
      style="margin-bottom: 15px"
      @check="handleCheckChange">
    </el-tree>
    <el-row style="text-align: right">
      <el-button style="margin-right: 10px" type="primary" @click="applyPower">确定</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-row>
  </el-card>
</template>

<script>
import debounce from 'lodash.debounce'

export default {
  name: "AssignPower",
  props: ['roleInfo'],
  data() {
    return {
      menuList: [], // 存储全部菜单的数据
      checkedArr: [], // 选中节点的数据

      // 节点的props配置
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    // 获取当前角色的权限列表
    async getPowerByRole() {
      let res = await this.$API.menu.apiGetMenuByRole(this.roleInfo.id)
      if (res.code === 20000) {
        // 递归遍历出数据中选中的所有的id
        let collectId = (target, arr = []) => {
          target.forEach(item => {
            if (item.select && item.level === 4) {
              arr.push(item.id)
            } else if (!item.children) {
              return
            } else {
              collectId(item.children, arr)
            }
          })
        }
        // 将获取到的id保存
        collectId(res.data.children, this.checkedArr)
      }
    },
    // 获取总权限列表
    async getAllPower() {
      let res = await this.$API.menu.apiGetMenu()
      if (res.code === 20000) {
        this.menuList = res.data.children
      } else {
        this.$message.error('数据获取失败')
      }
    },

    // 取消分配权限
    cancel() {
      // 重置数据
      this.resetData()
    },
    // 确定分配权限
    applyPower: debounce(function() {
      this.$API.menu.apiApplyPower(this.roleInfo.id, this.checkedArr.join(',')).then(result => {
        console.log(result)
        this.resetData()
        this.$message.success('更改权限成功')
      }).catch(e => {
        this.$message.error('添加失败')
      })
    }, 2000),

    // 节点被选中
    handleCheckChange(nodes, state) {
      this.checkedArr = state.checkedKeys
    },
    // 重置数据
    resetData() {
      this.$emit('update:flag', false)
      this.$emit('update:roleInfo', {})
      this._data = this.$options.data()
    }
  },
  mounted() {
    this.$nextTick(() => {
      // 获取当前角色的权限列表
      this.getPowerByRole()
      // 获取所有权限列表
      this.getAllPower()
    })
  }
}
</script>

<style scoped>

</style>
